$(function () {
    /**
     * $search.key   标签KEY
     * $search.value 标签值
     * $search.label 标签名称
     */
    var
        $search = parseSearch(),
        tag = ''
    ;
    $search.label = $search.label || '';

    var arg = { // 多分类匹配
        query: '/category/list?type1=31&size=' + maxSize,//分页查询URL,
        rendered: function () {
            if ($search.rmBtn) {
                $search.rmBtn.split(',').map(function (btn) {
                    if (btn == 'add') {
                        btns[0].remove();
                    }
                    if (btn == 'rm') {
                        btns[2].remove();
                    }
                })
            }
            $('.category-detail').each(function (index, item) {
                var $item = $(item);
                // onClick($('.category-detail'),function (e) {
                //     e.stopPropagation();
                var id = $item.data().id;
                // var that = this;
                $.get('/category/listDRBySourceId?targetId=' + id + '&type1=31&dataRtype1=31', function (res) {
                    console.log(res);
                    if (res.list && res.list.list) {
                        if (res.list.list.length != 0) {
                            $item.replaceWith('<span>' + _.pluck(res.list.list, 'name').join(',') + '<span>')
                        } else {
                            $item.replaceWith('<span>无<span>')
                        }
                    }
                })
            })
            if (window.categoryId && !$('[name=categoryId]').data('init')) {//
                var filterObj = lsGet(opt.lastSearchKey);
                getClassifiedQuery({url: '/category/listSummary?type1=31&size=10000'}, function (res) {
                    var categorys2 = res
                    selectpickerFn({
                        ele: $('[name=categoryId]'),
                        name: 'categoryId',
                        label: '请选择分类',
                        placeholder: '所有分类',
                        selected: categorys2.id || '',
                        list: categorys2,
                        change: function (id) {
                            console.log(id);
                            $('[name=categoryId]').val(id);
                            search({categoryId: id, page: 1}, true)
                        }
                    })
                })
            }
        },
        btns: [
            {
                label: '增加',
                class_: 'create',
                onClick: function () {
                    var $index = dialogForm(
                        {
                            title: "增加分类",
                            data: [
                                {
                                    type: 'text',
                                    label: '分类名称',
                                    require: true, // 是否必填
                                    placeholder: '请输入分类名称',
                                    name: 'name'
                                },
                                {
                                    type: 'text',
                                    label: '描述',
                                    placeholder: '请输入描述',
                                    name: 'desc1'
                                },
                                {
                                    type: 'text',
                                    label: '排序号',
                                    val: '0',
                                    placeholder: '请输入排序号',
                                    name: 'orderNum'
                                },

                            ],
                            submit: function (form) {
                                form.level = 1;
                                form.type1 = 'shop-category'; // 数据类型菜单
                                $.post('/category/add', form, function (res) {
                                    if (res.code == 200) {
                                        fnSuccess("操作成功");
                                        search({}, true);
                                        closeLayer($index);
                                    } else {
                                        fnFail("操作失败");
                                    }
                                })
                            }
                        });
                }
            },
            {
                label: '修改',
                class_: 'update',
                onClick: function () {
                    var $json = $(this).data('json');
                    if ($json.name == '批量上货导入') {
                        return alert('批量上货导入不能修改')
                    }
                    console.log($json);
                    var $index = dialogForm(
                        {
                            title: "修改商品分类",
                            data: [
                                {
                                    type: 'text',
                                    label: '分类名称',
                                    val: $json.name,
                                    require: true, // 是否必填
                                    placeholder: '请输入分类名称',
                                    name: 'name'
                                },
                                {
                                    type: 'text',
                                    label: '描述',
                                    val: $json.desc1 || '',
                                    placeholder: '请输入描述',
                                    name: 'desc1'
                                },
                                {
                                    type: 'text',
                                    label: '排序号',
                                    val: $json.orderNum || 0,
                                    placeholder: '请输入排序号',
                                    name: 'orderNum'
                                },
                            ],
                            submit: function (form) {
                                form.id = $json.id; // 数据类型菜单
                                $.post('/category/update', form, function (res) {
                                    if (res.code == 200) {
                                        fnSuccess("操作成功");
                                        search({}, true);
                                        closeLayer($index);
                                    } else {
                                        fnFail("操作失败");
                                    }
                                })
                            }
                        });
                }
            },
            {
                label: '删除',
                class_: 'delete',
                onClick: function () {
                    var $json = $(this).data('json');
                    if ($json.name == '批量上货导入') {
                        return alert('批量上货导入不能删除')
                    }
                    console.log($json);
                    if (confirm('确认删除？')) {
                        $.post('/category/delete/' + $json.id, {}, function (res) {
                            if (res.code == 200) {
                                search({}, true);
                                fnSuccess('删除成功！');
                            }
                        })
                    }
                }
            },
            {
                label: '增加二级分类',
                onClick: function () {
                    var $jon = $(this).data('json');
                    console.log($json);
                    var $json = {};
                    if ($jon.level == 2) {
                        $json = $jon;
                    }
                    var $index = dialogForm(
                        {
                            title: "增加二级分类",
                            data: [
                                {
                                    type: 'text',
                                    label: '二级分类',
                                    val: $json.name || '',
                                    require: true, // 是否必填
                                    placeholder: '请输入二级分类',
                                    name: 'name'
                                },
                                {
                                    type: 'text',
                                    label: '描述',
                                    val: $json.desc1 || '',
                                    placeholder: '请输入描述',
                                    name: 'desc1'
                                },
                                {
                                    type: 'text',
                                    label: '排序号' || 0,
                                    val: $json.orderNum,
                                    placeholder: '请输入排序号',
                                    name: 'orderNum'
                                },
                            ],
                            full: true,
                            submit: function (form) {
                                form.level = 2;
                                form.type1 = 'shop-category';
                                if ($jon.level == 1) { //  为一级菜单增加子菜单
                                    form.pId = $jon.id;
                                } else { // 修改子菜单
                                    form.id = $jon.id; // 数据类型菜单
                                }
                                //form.type1 = 'front-menu'; // 数据类型菜单
                                $.post($jon.level == 1 ? '/category/add' : '/category/update', form, function (res) {
                                    if (res.code == 200) {
                                        fnSuccess("操作成功");
                                        search({}, true);
                                        closeLayer($index);
                                    } else {
                                        fnFail("操作失败");
                                    }
                                })
                            }
                        });
                }
            },
            {
                label: '上架/下架',
                class_: 'update',
                onClick: function () {
                    var $jon = $(this).data('json');
                    if ($jon.name == '批量上货导入') {
                        return alert('批量上货导入不能上架')
                    }
                    var $json = {};
                    var ti = ['targetId=' + $jon.id, 'type1=shop-category', 'isShow=' + ($jon.isShow == '1' ? '0' : '1')];
                    $.get('/statistic1/set?' + ti.join('&'), function (res) {
                        if (res.code == 200) {
                            console.log('ok!');
                            fnSuccess(($jon.isShow == '1' ? '上架' : '下架') + '操作成功')
                            search({}, true);
                        }
                    })
                }
            },
            {
                label: '移动',
                onClick: function () {
                    var $jon = $(this).data('json');
                    var $json = $jon, level = parseInt($jon.level);
                    var $index = dialogForm(
                        {
                            title: "移动",
                            data: [
                                {
                                    type: 'text',
                                    label: '移动至',
                                    val: $json.name || '',
                                    require: true, // 是否必填
                                    placeholder: '请选择一级目录',
                                    name: 'pId'
                                },
                            ],
                            full: true,
                            shown: function () {
                                selectGoods({
                                    name: 'pId',
                                    url: '/category/list?type1=shop-category&level=' + (level - 1),
                                    selected: $json.pId,
                                    key: 'KEY' + Math.random()
                                })
                            },
                            submit: function (form) {
                                //$json.pId = form.pId;
                                form.id = $json.id;
                                $.post('/category/update', form, function (res) {
                                    if (res.code == 200) {
                                        fnSuccess("移动操作成功");
                                        search({}, true);
                                        closeLayer($index);
                                    } else {
                                        fnFail("移动操作失败");
                                    }
                                })
                            }
                        });
                }
            },
            {
                label: '树形结构查看',
                onClick: function () {
                    window.location.href = '../setting/category.html'
                }
            },
            {
                label: '分类图标',
                class_: 'upload',
                onClick: function () {

                    var $json = $(this).data('json');
                    imageSelector({
                        multi: false,
                        title: '',
                        body: $('#imgs').html()
                    }, {
                        ok: function (arr, cb, t) {
                            arr = arr || [];
                            arr.map(function (item) {
                                initImg(item.url, false, item.id)
                                cb(t)
                            })
                        },
                        cancel: function (cb, t) {
                            cb(t)
                        },
                        dbclick: function ($ele) {
                            $ele.find('img.appendImg').attr('src')
                            $ele.find('img.appendImg').attr('id')

                        },
                        click: function ($ele) {
                            $ele.find('img.appendImg').attr('src')
                            $ele.find('img.appendImg').attr('id')
                            var $id = $ele.find('img.appendImg').attr('id')
                            var $url = $ele.find('img.appendImg').attr('src')
                            if (!$url) {
                                return;
                            }
                            $.post('/category/update', {id: $json.id, url: $url}, function (res) {
                                if (res.code == 200) {
                                    search({}, true);
                                    fnSuccess('上传成功～')
                                } else {
                                    fnFail(res.error || '上传失败！')
                                }
                            })

                        }
                    })
                },

            },
        ],
        destroyBtn: function () {
            disableBtn(btns[5]);
            disableBtn(btns[4]);
            disableBtn(btns[3]);
            disableBtn(btns[2]);
            disableBtn(btns[7]);
            disableBtn(btns[1]);
        },
        createBtn: function (_this) {
            var $item = $(_this).data('json');
            enableBtn(btns[1], $item);
            enableBtn(btns[2], $item);
            enableBtn(btns[4], $item);
            enableBtn(btns[7], $item);
            if ($item.level != '0') {
                enableBtn(btns[5], $item);
            } else {
                disableBtn(btns[5]);
            }
            if ($item.level == 1 && $item.type1 == 'shop-category') {
                enableBtn(btns[3], $item);
            }
        },
        listFilter: function (res) {
            var t0 = _.filter(res, function (itme) {
                return itme.level == 0;
            })
            var t = _.filter(res, function (itme) {
                return itme.level == 1;
            })
            var tg = _.filter(res, function (itme) {
                return itme.level == 2;
            });
            tg = _.groupBy(tg, 'pId');
            t = _.groupBy(t, 'pId');
            // t = _.sortBy(t, 'orderNum').reverse();
            // t = _.sortBy(t, 'orderNum').reverse();
            t0 = _.sortBy(t0, 'orderNum').reverse();
            t1 = [];
            t0.map(function (item0) {
                t1.push(item0);
                if (t[item0.id] && t[item0.id].length) {
                    t[item0.id].map(function (item) {
                        t1.push(item);
                        if (tg[item.id]) { //
                            t1.push(_.sortBy(tg[item.id], 'orderNum').reverse())
                        }
                    })
                }
            })
            return _.flatten(t1, true);
        },
        fields: [
            {
                name: 'name', label: '名称',
                enableSearch: true,
                fnStyle: function (item) {
                    return item.level == 2 ? ";padding-left:0px;" : '';
                },
                filter: function (item) {
                    if (item.level == 2) {
                        return item.level == 2 ? ('<div style="font-size: 14px;font-weight: 600;padding-left: 40px;margin-left: 40px;">' + item.name + '</div>') : '<div style="font-size: 14px;font-weight: 600;' + (item.name == '批量上货导入' ? 'color: red;' : '') + '">' + item.name + '</div>';
                    }
                    return item.level == 1 ? ('<div style="font-size: 14px;font-weight: 600;padding-left: 20px;margin-left: 20px;">' + item.name + '</div>') : '<div style="font-size: 14px;font-weight: 600;' + (item.name == '批量上货导入' ? 'color: red;' : '') + '">' + item.name + '</div>';
                }
            },
            {
                name: 'level', label: '层级',
                filter: function (item) {
                    return item.level;
                },
                fnStyle: function (item) {
                    return item.level == 1 ? ";" : ''
                }
            },
            {
                name: 'isShow', label: '状态',
                filter: function (item) {
                    return item.isShow == 1 ? "<span class='label label-success'>上架</span>" : "<span class='label label-warning'>下架</span>"
                },
            },
            {
                name: 'desc1', label: '描述',
                fnStyle: function (item) {
                    if (item.level == 2) {
                        return ';padding-left:100px;';
                    }
                    return item.level == 1 ? ";padding-left:50px;" : ''
                }
            },
            {
                name: 'url', label: '分类图标',
                filter: function (item) {
                    if (item.url) {
                        return '<a target="_blank" href="' + item.url + '" title="点击预览"><img style="height:60px;border-radius: 5px" src="' + item.url + '"></a>'
                    } else {
                        return getDefaultImgStr();
                    }
                }
            },

            {
                name: 'orderNum', label: '排序号',
                fnStyle: function (item) {
                    if (item.level == 2) {
                        return ';padding-left:100px;';
                    }
                    return item.level == 1 ? ";padding-left:50px;" : ''
                }
            },
        ],
    };

    window.btns = arg.btns.map(function (item) { // 设置分类
        var btn = genBtn(item);
        if (item.onClick) onClick(btn, item.onClick)
        return btn;
    });
    setBtn(btns);

    function search(obj, isForce, isExport) {
        arg.destroyBtn();
        return gSearch({
            table: '.table',
            url: arg.query,
            query: obj,
            isForce: isForce,
            isExport: isExport,
            render: function (res) {
                var _$table = $('.table-responsive .table');
                destroyBtn();
                if (!!arg.beforeRender) res = arg.beforeRender(res);
                _$table.$table($.extend(TABLE_SETTING, {
                    checkbox: true, // 是否显示复选框
                    seqNum: true, // 是否显示序号
                    sort: search, //排序回调函数
                    destroyBtn: arg.destroyBtn, //禁用按钮
                    createBtn: arg.createBtn, // 启用她扭
                    toolbar: '.toolbar',
                    enableSetting: true,//允许自定义显示列
                    search: search,
                    showSearchComplex: true,
                    rendered: arg.rendered || function () {
                    },
                    fields: arg.fields,
                    data: arg.listFilter ? arg.listFilter(res) : res || [],
                }, arg.dateSearch ? { // 允许日期区间搜索
                    complexItems: [
                        {label: "", name: 'date', dateRange: true},
                    ]
                } : {}));
            }
        }, obj.first ? false : true);
    }

    search({}, true);
    function initImg(url, isThumbnail, fileId) {
        var item = ejs.render($('#img-item-template').html(), {
            url: url,
            isThumbnail: isThumbnail,
            id: fileId,
        });

        $(item).insertBefore($('.item-trigger').closest('.col-sm-4'));
    }
    selectGoodsClass()
    function selectGoodsClass() {
        if ($search.id) {
            $.get('/dataR/selectBy?type1=shop-category&targetId=' + $search.id, function (res) {
                $sourceId = _.pluck(res.list, 'sourceId');
                generateCategory($sourceId);
            })
        } else {
            generateCategory();
        }

        function generateCategory(categoryId) {
            getClassifiedQuery({url: '/category/listSummary?type1=31&size=10000'}, function (res) {
                var categorys2 = res
                selectpickerFn({
                    multiple: true,
                    ele: $('[name=categoryId]'),
                    name: 'categoryId',
                    label: '请选择分类',
                    placeholder: '所有分类',
                    selected: categoryId || '',
                    list: categorys2,
                    change: function (id) {
                        console.log(id);
                        $('[name=categoryId]').val(id);
                    }
                })
            })
        }
    }

})

